# -*- encoding: utf-8 -*-
"""
@File        : os_status_unit.py
@License     : (C)Copyright 2021 LeeRoc (cn) Lipeng
@Modify Time : 2021/8/1 10:59 上午 
@Author      : LeeRoc
@Version     : 1.0
@Description :

info: 32.2%
      803.4M
"""
import psutil
import socket


def get_localhost_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip


# cpu信息
def get_cpu_info():
    cpu_percent = psutil.cpu_percent(interval=1)
    # cpu_info = "CPU使用率：%i%%" % cpu_percent
    # print(cpu_info)
    return str(cpu_percent) + '%'


# 内存信息
def get_memory_info():
    virtual_memory = psutil.virtual_memory()
    # virtual_memory_count = bytes2human(virtual_memory.total)
    # used_memory = bytes2human(virtual_memory.used)
    free_memory = bytes2human(virtual_memory.free)
    # memory_percent = virtual_memory.percent

    # memory_info = "总共内存：%s, 内存使用：%s，使用率%0.1f%%，剩余内存：%s" % (
    # virtual_memory_count, used_memory, memory_percent, free_memory)
    # print(memory_info)
    return free_memory


def bytes2human(n):
    """
    内存单位转换
    :param n:
    :return:
    """
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%.1f%s' % (value, s)
    return '%sB' % n
